const mysql = require('mysql')

module.exports = class Model {
  // 连接对象
  static conn = null

  // 连接数据库
  static connect() {
    Model.conn = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '123456',
      database: 'blog'
    })
    Model.conn.connect(err => {
      if(err){
        console.log('数据库连接失败')
        console.log(err)
      }
    })
  }
  // 关闭连接
  static close() {
    if(Model.conn != null) {
      Model.conn.end()
    }
  }
  // 查询
  static query(sql, params=[]) {
    return new Promise((resolve, reject) => {
      this.connect()
      Model.conn.query(sql, params, (err, res) => {
        if(err){ reject(err) }
        else { resolve(res) }
      })
      this.close()
    })
  }
}